<template>
  <div>
    <!-- 分配权限弹出层 -->
    <el-dialog title="分配权限" :visible="showattribute" @close="closepop">
      <el-tree
        ref="tree"
        :data="permissionList"
        node-key="id"
        :show-checkbox="true"
        check-strictly
        :props="defaultProps"
        default-expand-all=""
      />

      <span slot="footer">
        <el-button @click="$emit('update:showattribute', false)">
          取消
        </el-button>
        <el-button type="primary" @click="submitpermission">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getPermissionList } from '@/api/permission'
import { getDepart } from '@/utils'
import { getRoleDetail, assignPerm } from '@/api/setting'
export default {
  props: {
    showattribute: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      roleId: '',
      permissionList: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    }
  },
  created () {
    this.getPerList()
  },
  methods: {
    async submitpermission () {
      const res = this.$refs.tree.getCheckedKeys()
      try {
        // {id:角色id, permIds:[] 所有选中的节点的id组成的数组}
        await assignPerm({ id: this.roleId, permIds: res })
        this.$emit('update:showattribute', false)
        this.$message.success('权限分配成功')
      } catch (error) {
        console.log(error)
      }
    },
    async setChecked (id) {
      this.roleId = id
      try {
        const res = await getRoleDetail(id)
        this.$refs.tree.setCheckedKeys(res.permIds)
      } catch (error) {
        console.log(error)
      }
    },
    async getPerList () {
      try {
        const res = await getPermissionList()
        console.log(res)
        this.permissionList = getDepart(res)
      } catch (error) {
        console.log(error)
      }
    },
    closepop () {
      this.$refs.tree.setCheckedKeys([])
      this.$emit('update:showattribute', false)
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
